/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-11-28
 * Time: 13:48
 */
public class MyBlockingQueue {

    private int[] task = null;
    private int head = 0;
    private int tail = 0;
    int size = 0;
    private static final int DEFAULT_CAPACITY = 500;

    private Object locker = new Object();

    public MyBlockingQueue() {
        task = new int[DEFAULT_CAPACITY];
    }

    public MyBlockingQueue(int capacity) {
        task = new int[capacity];
    }

    //入队列方法
    public void put(int runnable) throws InterruptedException {
        synchronized (locker) {
            //判断队列是否满了
            while (size == task.length) {
                locker.wait();
            }
            //入队列核心操作
            task[tail++] = runnable;
            if (tail >= task.length) {
                tail = 0;
            }

            size++;
            locker.notify();
        }
    }

    //出队列方法
    public int take() throws InterruptedException {
        synchronized (locker) {
            //判断队列是否为空
            while (size == 0) {
                locker.wait();
            }
            //出队列核心操作
            int ret = task[head++];
            if (head >= task.length) {
                head = 0;
            }

            size--;
            locker.notify();
            return ret;
        }
    }

}
